﻿using System.Text.Json.Serialization;
using Core.Caching;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Identity.Menus.Caching;
using Core.Identity.Roles.Dtos;
using Core.Models;
using Mapster;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Core.Identity.Roles.Features.Queries.GetMenus;

/// <summary>
/// 角色菜单
/// </summary>
public class GetRoleMenusQuery : ICacheableRequest<Result<IEnumerable<RoleMenuDto>>>
{
    /// <summary>
    /// 缓存键
    /// </summary>
    [JsonIgnore]
    public string CacheKey => MenusCacheKey.GetRoleMenusCacheKey;

    /// <summary>
    /// 缓存选项
    /// </summary>
    [JsonIgnore]
    public IEnumerable<string>? Tags => MenusCacheKey.Tags;
}

public class GetRoleMenusQueryHandler :
         IRequestHandler<GetRoleMenusQuery, Result<IEnumerable<RoleMenuDto>>>
{
    private readonly IIdentityDbContext _context;

    public GetRoleMenusQueryHandler(
        IIdentityDbContext context)
    {
        _context = context;
    }

    public async Task<Result<IEnumerable<RoleMenuDto>>> Handle(GetRoleMenusQuery request, CancellationToken cancellationToken)
    {
        return await Result<IEnumerable<RoleMenuDto>>
            .SucceedAsync((await _context.Permissions
            .AsNoTracking()
            .OrderByDescending(x => x.Sort)
            .ToListAsync(cancellationToken))
            .Adapt<IEnumerable<RoleMenuDto>>());
    }
}
